package com.coder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.coder.entity.User;
import com.coder.service.UserService;
import com.coder.utils.result.Res;
import com.coder.utils.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 王令
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User loginUser = userService.login(user);
        if (loginUser == null){
            return Res.error("邮箱或密码不正确");
        }
        return Res.ok(loginUser);
    }


    @PostMapping("/reg")
    public Result register(@RequestBody User user){
        return userService.register(user)? Res.ok(): Res.error("邮箱已存在");
    }


    /**
     * 咨询师数据
     * @return
     */
    @GetMapping("/consultant")
    public Result consultant(){
        return Res.ok(userService.consultant());
    }


    @GetMapping("/forgetValidate")
    public Result forgetValidate(User user){
        if (userService.forgetValidate(user)){
            return Res.ok();
        }else {
            return Res.error("用户不存在，或信息不一致");
        }
    }

    @GetMapping("/changePassword")
    public Result changePassword(User user){
        if (userService.changePassword(user)){
            return Res.ok();
        }else {
            return Res.error("操作失败");
        }
    }

    /**
     * 申请咨询师
     * @param user 实体类
     * @return 处理结果
     */
    @PutMapping("/updateIdentity")
    public Result updateIdentity(User user) {
        boolean flag = userService.updateById(user);
        if (flag) {
            return Res.ok();
        } else {
            return Res.error("操作失败");
        }
    }

    /**
     * 根据邮箱查询用户信息
     * @param email 用户邮箱
     * @return 用户对象
     */
    @GetMapping("/{email}")
    public Result changePassword(@PathVariable("email") String email) {
        User user = userService.getOne(new QueryWrapper<User>().eq(Strings.isNotBlank(email), "email", email));
        if (user!=null) {
            return Res.ok(user);
        } else {
            return Res.error("操作失败");
        }
    }


}
